package com.lee.aop;

import com.lee.entity.ResponseWrapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * TODO
 *
 * @className: ResponseResultHandler
 * @author: lx
 * @date: 2021-01-15
 **/
@ControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<ResponseEntity> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        // 判断是否标注了注解
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        Object attribute = request.getAttribute("RESPONSE-RESULT-ANN");
        return attribute == null ? false : true;
    }

    @Override
    public ResponseEntity beforeBodyWrite(ResponseEntity responseEntity, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        return new ResponseEntity(ResponseWrapper.ok(responseEntity).build(), HttpStatus.OK);
    }
}
